// AMap 初始化代码
let map;
let polylines = [];
let fileSegmentMap = {};  // 存储文件索引到段的映射
const batchSize = 5;  // 每次加载的文件数量
let currentBatch = 0;

function initMap() {
    map = new AMap.Map('mapContainer', {
        zoom: 8.50,
        center: [114.175135, 25.02458],
        pitch: 40,
        showLabel: false,
        mapStyle: 'amap://styles/45311ae996a8bea0da10ad5151f72979',
        viewMode: '2D',
    });

    // 读取所有文件并绘制路线
    readCoordinatesFromFilesAndDraw();
}

function readCoordinatesFromFilesAndDraw() {
    const folderPath = './GPSdata/endData/';
    const files = [
        '百旺东路_reformatted.txt', '百旺西路_reformatted.txt', '百旺中路_reformatted.txt',
        '韶关大道南_reformatted.txt', 'G45_reformatted.txt', 'G220_reformatted.txt',
        'G2042_reformatted.txt', 'G6011_reformatted.txt', 'S10_reformatted.txt',
        's246_reformatted.txt', 's343_reformatted.txt', 'x312_reformatted.txt',
        '升平立交-石岭立交.txt', 'G4.txt', 'G78.txt', 'G78_up.txt', 'G4023_up.txt', 'G4023.txt', 'G4521.txt'
    ];

    // 按批次加载文件
    loadNextBatch(files, folderPath);
}

function loadNextBatch(files, folderPath) {
    const startIndex = currentBatch * batchSize;
    const endIndex = Math.min(startIndex + batchSize, files.length);
    const currentFiles = files.slice(startIndex, endIndex);

    if (currentFiles.length > 0) {
        // 加载当前批次的文件
        currentFiles.forEach((file, index) => {
            const filePath = folderPath + file;

            fetch(filePath)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`Network response was not ok for file: ${filePath}`);
                    }
                    return response.text();
                })
                .then(text => {
                    const coordinates = processFileContent(text);

                    if (coordinates.length > 1) {
                        const segments = validateAndSegmentCoordinates(coordinates);
                        segments.forEach(segment => drawSegment(segment, startIndex + index));

                        // 存储文件索引到段的映射
                        if (!fileSegmentMap[startIndex + index]) {
                            fileSegmentMap[startIndex + index] = [];
                        }
                        fileSegmentMap[startIndex + index].push(...segments);

                        // 添加到下拉框
                        const select = document.getElementById('roadSelect');
                        const option = document.createElement('option');
                        option.value = startIndex + index;  // 使用索引作为值
                        option.text = removeFileExtension(file);  // 去掉文件名中的后缀
                        select.appendChild(option);
                    } else {
                        console.warn(`Not enough valid coordinates in file: ${filePath}`);
                    }
                })
                .catch(error => console.error('Error fetching or processing file:', error));
        });

        // 处理完当前批次后，加载下一批
        currentBatch++;
        setTimeout(() => loadNextBatch(files, folderPath), 200);  // 添加一个短暂的延时
    } else {
        // 添加下拉框事件监听器
        document.getElementById('roadSelect').addEventListener('change', function(event) {
            highlightSelectedRoad(event.target.value);
        });
    }
}

function removeFileExtension(filename) {
    return filename.replace('_reformatted.txt', '').replace('.txt', '');  // 去掉特定后缀
}

function processFileContent(text) {
    const lines = text.split('\n').filter(line => line.trim() !== ''); // 去除空行
    return lines.map(line => {
        try {
            const coord = JSON.parse(line);
            if (Array.isArray(coord) && coord.length === 2 &&
                !isNaN(coord[0]) && !isNaN(coord[1])) {
                return coord;
            } else {
                console.warn('Invalid coordinate format:', line);
            }
        } catch (e) {
            console.error('Failed to parse line:', line);
        }
        return null;
    }).filter(coord => coord !== null);
}

function validateAndSegmentCoordinates(coordinates, lonThreshold = 0.01, latThreshold = 0.01, connectThreshold = 0.05) {
    if (coordinates.length < 2) {
        return [];
    }

    const segments = [];
    let currentSegment = [coordinates[0]];

    for (let i = 1; i < coordinates.length; i++) {
        const lonDiff = Math.abs(coordinates[i][0] - coordinates[i - 1][0]);
        const latDiff = Math.abs(coordinates[i][1] - coordinates[i - 1][1]);

        if (lonDiff <= lonThreshold && latDiff <= latThreshold) {
            currentSegment.push(coordinates[i]);
        } else {
            if (currentSegment.length > 1) {
                segments.push(currentSegment);
            }
            currentSegment = [coordinates[i]];
        }
    }

    if (currentSegment.length > 1) {
        segments.push(currentSegment);
    }

    // 连接相邻段的末点和起点
    for (let j = 1; j < segments.length; j++) {
        const prevSegment = segments[j - 1];
        const currentSegment = segments[j];
        const prevEndPoint = prevSegment[prevSegment.length - 1];
        const currStartPoint = currentSegment[0];

        const lonDiff = Math.abs(currStartPoint[0] - prevEndPoint[0]);
        const latDiff = Math.abs(currStartPoint[1] - prevEndPoint[1]);

        if (lonDiff <= connectThreshold && latDiff <= connectThreshold) {
            prevSegment.push(...currentSegment);
            segments.splice(j, 1);
            j--;
        }
    }

    // 尝试连接非直接相邻的段
    for (let i = 0; i < segments.length - 1; i++) {
        let segmentA = segments[i];
        for (let j = i + 1; j < segments.length; j++) {
            let segmentB = segments[j];
            const endA = segmentA[segmentA.length - 1];
            const startB = segmentB[0];

            const lonDiff = Math.abs(endA[0] - startB[0]);
            const latDiff = Math.abs(endA[1] - startB[1]);

            if (lonDiff <= connectThreshold && latDiff <= connectThreshold) {
                segmentA = segmentA.concat(segmentB);
                segments[i] = segmentA;
                segments.splice(j, 1);
                j--; // 重新检查合并后的段
            }
        }
    }

    return segments;
}

function drawSegment(segment, colorIndex) {
    const color = '#0000FF';  // 蓝色

    const polyline = new AMap.Polyline({
        path: segment,
        strokeColor: color,
        strokeWeight: 5,
        strokeOpacity: 0.8,
    });

    polyline.setMap(map);
    polylines.push(polyline);
}

function highlightSelectedRoad(index) {
    const selectedSegments = fileSegmentMap[index] || [];

    polylines.forEach((polyline, i) => {
        if (selectedSegments.includes(polyline.getPath())) {
            polyline.setOptions({
                strokeWeight: 8,
                strokeColor: '#FF0000',  // 红色
                zIndex: 100
            });
        } else {
            polyline.setOptions({
                strokeWeight: 5,
                strokeColor: '#0000FF',  // 恢复为蓝色
                zIndex: 10
            });
        }
    });
}

// 等待页面加载完毕后再初始化地图
window.onload = function () {
    initMap();
};
